package tcln.sors.client.core.component.form;

import java.awt.Component;
import java.util.Collection;
import java.util.Vector;

import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JList;

import tcln.commons.dataobject.NamedObject;

/**
 * @author Truong Chau Lien Ngoc (lienngoc@gmail.com)
 * @param <T>
 *            Named object type.
 */
@SuppressWarnings("serial")
public class NamedObjectComboBox<T extends NamedObject> extends JComboBox {

    /**
     * constructs this combobox without data.
     */
    public NamedObjectComboBox() {
        super();
        setRenderer(new NamedObjectListCellRenderer());
    }

    /**
     * constructs this combobox with initial data.
     * 
     * @param namedObjects
     */
    public NamedObjectComboBox(Collection<T> namedObjects) {
        super(new Vector<T>(namedObjects));
        setRenderer(new NamedObjectListCellRenderer());
    }

    /**
     * Sets all objects to be shown. Old data is removed.
     * 
     * @param namedObjects
     */
    public void setObjects(Collection<T> namedObjects) {
        removeAllItems();
        for (T t : namedObjects) {
            addItem(t);
        }
    }

    /**
     * Returns the selected object if any.
     * 
     * @return
     */
    public T getSelectedObject() {
        Object obj = getSelectedItem();
        return (T) obj;
    }

    /**
     * Sets the object to be selected by the component.
     * 
     * @param obj
     */
    public void setSelectedObject(T obj) {
        setSelectedItem(obj);
    }

    private static class NamedObjectListCellRenderer extends DefaultListCellRenderer {
        /**
         * {@inheritDoc}
         */
        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if (value instanceof NamedObject) {
                setText(((NamedObject) value).getName());
            }
            return this;
        }
    }
}
